#!/bin/bash
#
# 下载、运行、停止基础镜像
UP_DOWN="$1"

CONTAINER_IDS=
IMAGES_NAME="rabbitmq:3.7.7-management openzipkin/zipkin" # 必备基础镜像

COMPOSE_FILE_ZIPKIN=docker-compose-zipkin.yml

function dockerPull() {
  for IMAGES in $IMAGES_NAME; do
      echo "==> IMAGE: $IMAGES"
      echo
      docker pull $IMAGES
  done
}

function dockerRun() {
  echo "docker run rabbitmq default account:admin password:admin"
  docker run -d --name rabbitmq  -p 5672:5672 -p 15672:15672 -v `pwd`/data:/var/lib/rabbitmq --hostname myRabbit  -e RABBITMQ_DEFAULT_USER=admin -e RABBITMQ_DEFAULT_PASS=admin rabbitmq:3.7.7-management
#  echo
#  echo "docker run mysql default account:root password:6636256"
#  docker run -p 3307:3306 --name mysql5.7.21 -v /Users/caochong/docker_v/mysql/conf:/etc/mysql/conf.d -e MYSQL_ROOT_PASSWORD=6636256 -d mysql:5.7.21
#  echo
#  echo "docker run redis"
#  docker run -d --name redis -p 6379:6379 redis:latest
#  echo
#  echo "docker-compose run zipkin"
#  docker-compose -f $COMPOSE_FILE_ZIPKIN up -d 2>&1
}

function dockerStopAndRm() {
  for NAMES in $IMAGES_NAME; do
      CONTAINER_ID=$(docker ps | grep $NAMES | awk '{print $1}')
      if [ "$CONTAINER_ID" = "" ]; then
        echo ""
      else
        CONTAINER_IDS+=" "$CONTAINER_ID
      fi
  done
  echo "==> IMAGES_NAME: $IMAGES_NAME"
  echo "==> CONTAINER_IDS: $CONTAINER_IDS"
  echo
  if [ -z "$CONTAINER_IDS" -o "$CONTAINER_IDS" = "" ]; then
      echo "---- No containers available for deletion ----"
  else
      docker stop  $CONTAINER_IDS
      docker rm -f $CONTAINER_IDS
  fi
}

function pull() {
    echo "===> Pull Images"
    dockerPull
}

function up() {
    echo "===> Run Images"
    dockerRun
}

function build() {
    echo "===> implement docker_build_run.sh"
    /bin/sh ./docker_build_run.sh up
}

function down() {
    echo "===> Stop And Rm Container"
    dockerStopAndRm
}

function printHelp() {
	echo "pull/up/down/build"
}

if [ "${UP_DOWN}" == "pull" ]; then
    pull

    echo
    echo "===> List out docker images"
    docker images
elif [ "${UP_DOWN}" == "down" ]; then
	down

	echo
    echo "===> List out docker ps -a"
    docker ps -a
elif [ "${UP_DOWN}" == "build" ]; then
	build

elif [ "${UP_DOWN}" == "up" ]; then
	up

	echo
    echo "===> List out docker ps -a"
    docker ps -a
else
	printHelp
	exit 1
fi

